// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
    env: "yiliaojiufeng-6gt0kj1l1df8b7b7",
    traceUser: true,
})

// 云函数入口函数
const db = cloud.database()
exports.main = async (event, context) => {
    const _ = db.command
    const $ = db.command.aggregate
    var now = new Date().getTime()

    var idlist = await db.collection('readHistory').aggregate().match({
            time: _.gte(now - 1 * 24 * 60 * 60 * 1000).and(_.lte(now))
        })
        .group({
            _id: '$newsId',
            count: $.sum(1),
        }).sort({
            count: -1,
        }).limit(3).end()
    console.log(idlist)

    var result = []
    
    for (var i =0;i<idlist.list.length;i++){
        await db.collection('news_article').where({
            _id: idlist.list[i]._id
        }).get().then(res => {
            result.push({
                title: res.data[0].title,
                newsId: res.data[0]._id
            })
        })
    }

    return result
}

/* db.collection('readHistory').where({
    time: _.gte(now - 1 * 24 * 60 * 60 * 1000).and(_.lte(now))
}).get().then(res => {
    console.log("信息查询:", res)
}) */